/*******************************
* Utilities for javascripts in the iRODS enginFrame plugin
* Author: Mike Conway - RENCI (www.renci.org)
* Date: 07/25/2009
*/


function errorDataObject() {
	this.errorMajor = "";
	this.errorMinor = "";
	this.status = "0";
}

/*****
* Error trapping function, scrub HTML from an AJAX call, looking for enginFrame generated error tags
*
* @param returnHtmlData - raw html returned from an AJAX call
* @return formatted errorDat object, will be 0 if ok, W if warning, E if error
*/
function checkAppError(returnHtmlData) {
	var errorData = new errorDataObject();
	errorData.errorMajor = "";
	errorData.errorMinor = "";
	errorData.status = "0";
	var retIdx = returnHtmlData.indexOf("large-app-error");
	
	if (retIdx != -1) {
		errorData.errorMajor = returnHtmlData.substring(retIdx + 17, returnHtmlData.indexOf("</h3>", retIdx));
		var minorIdx = returnHtmlData.indexOf("small-app-error");
		errorData.errorMinor = returnHtmlData.substring(minorIdx + 17, returnHtmlData.indexOf("</pre>", minorIdx));
	}
	
	
	// if an error occurred, certain conditions should be treated as a warning, versus an application error
	if (errorData.errorMajor > "") {
		if (errorData.errorMinor.indexOf("CAT_NO_ROWS_FOUND") != -1) {
			errorData.status = "W";
		} else if (errorData.errorMinor.indexOf("The output size of this service exceeds the maximum limit defined in EnginFrame configuration") != -1) {
			errorData.status = "W";
		} else {
			errorData.status = "E";
		}
	} 
	
	return errorData;
}

/*********
* Helper function to take a number, with or without . point, and format with commas
* @param nStr - number to maniuplate
* @return number formatted with commas
*/

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/****************
* Helper function to trim leading and trailing spaces.  Useful, for example, for putting data into id fields properly
* @param nStr - value to trim
* @return trimmed value of nStr
*/
function trim(nStr) {
	return nStr.replace(/^\s+|\s+$/g,"");
}
